package ltd.hxya.novel.springsecurity.utils;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import ltd.hxya.novel.common.utils.BaseUtils;
import ltd.hxya.novel.common.vo.OperLog;
import ltd.hxya.novel.common.anno.OperLogAnno;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

public class OperationUtils {

    private static OperLog operName;

    /**
     * 根据请求的信息获取操作
     */
    public static OperLog getOperation(OperLogAnno operLogAnno){
        OperLog operLog = new OperLog();
        HttpServletRequest request = getRequest();
        operLog.setOperIp(request.getRemoteAddr());
        operLog.setLogId(IdWorker.getIdStr());
        operLog.setOperTime(LocalDateTime.now());
        operLog.setRequestMethod(request.getMethod());
        operLog.setOperUrl(request.getRequestURI().toString());
        operLog.setBusinessType(operLogAnno.operator().code);
        operLog.setTitle(operLogAnno.module().moduleName);
        operLog.setOperDesc(operLogAnno.desc());
        operLog.setBusinessType(0);
        setOperName(operLog);
        return operLog;
    }

    public static HttpServletRequest getRequest(){
        return getRequestAttributes().getRequest();
    }

    public static ServletRequestAttributes getRequestAttributes(){
      return  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

    }

    public static void setOperName(OperLog operLog) {
        String username = SecurityUtils.principal().getUsername();
        operLog.setOperName(username);
    }
}
